package top.itaso.lib.widget.tpv;

import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;

import androidx.annotation.Nullable;

import java.util.Date;

import top.itaso.lib.widget.R;

/**
 * @Description: IWB 系统设置 统一封装 页面 TitleBar，默认显示 返回键 + 标题，其中：
 * 1、标题内容需调用 setTitleContent 设置标题内容
 * 2、隐藏返回键时 重写 isShowBack 并 return false
 * 3、自定义排版，请 使用 addTitleBarXXX()
 * @Author: itsdf07
 * @CreateDate: 2022/8/18
 * @mark 原则上该控件是为了规范 titlebar 的统一使用，所以 childview 相关业务应该尽可能消费在控件中，尽量不让外部持有并控制，所以慎重开放相关属性和对象（子视图）
 */
public class TpvSettingsTitleBarView extends LinearLayout {
    private final String TAG = this.getClass().getSimpleName();
    /**
     * TitleBar 中 填充的自定义子视图需要的默认右边距距离（含标题和按钮）
     */
    private int childviewRightmargin;

    private LinearLayout layoutTitleBarContent;
    private LinearLayout layoutTitleBarRight;

    private ImageView btnBack;
    private TextView tvTitleContent;
    /**
     * 预留属性：标记 内容是否已添加完成
     */
    private boolean isLayoutReady;

    /**
     * 返回键事件回调
     */
    private IOnBackCallback iOnBackCallback;
    /**
     * 暗门事件回调
     */
    private IOnPrivateMarkCallback iOnPrivateMarkCallback;

    /**
     * 返回事件
     */
    public interface IOnBackCallback {
        void onBack();
    }

    /**
     * 暗门指令
     */
    public interface IOnPrivateMarkCallback {
        /**
         * 打开暗门
         */
        void onPrivateMarkOpen();
    }

    public TpvSettingsTitleBarView(Context context) {
        this(context, null);
    }

    public TpvSettingsTitleBarView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public TpvSettingsTitleBarView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        childviewRightmargin = getResources().getDimensionPixelSize(R.dimen.dimen_space_middle);
        isLayoutReady = false;
        setOrientation(LinearLayout.HORIZONTAL);
        setFocusable(true);
        initView();
        this.setOnFocusChangeListener(new OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                boolean btnBackIsVisible = (btnBack.getVisibility() == View.VISIBLE);
                Log.v(TAG, "onFocusChange: >>>>>>btnBack is " + (btnBackIsVisible ? "visible" : "invisible"));
                Log.d(TAG, "onFocusChange: >>>>>>" + v + " focus state is " + hasFocus);
                if (btnBackIsVisible && hasFocus) {
                    btnBack.requestFocus();
                }
            }
        });
    }

    /**
     * TitleBar 自定义视图全部布局完成之后调用
     */
    public void setLayoutReadyOk() {
        Log.d(TAG, "setLayoutReadyOk: >>>>>>" + this + " is ready ok");
        isLayoutReady = true;
        updateViewStatus();
    }

    /**
     * 添加 TitleBar 标题部分的 自定义控件，默认清空 childView
     *
     * @param views 子视图
     * @return
     */
    public TpvSettingsTitleBarView addTitleBarContent(View... views) {
        Log.v(TAG, "addTitleBarContent: >>>>>>views.length=" + views.length);
        return addTitleBarContent(true, views);
    }

    /**
     * 添加 TitleBar 标题部分的 自定义控件
     *
     * @param isRemoveChildView 添加前是否清空 childView，true-清空，false-不清空，顺序添加，并重写 onDefaultTitleContent 提供标题内容
     * @param views             子视图
     * @return
     */
    public TpvSettingsTitleBarView addTitleBarContent(boolean isRemoveChildView, View... views) {
        Log.d(TAG, "addTitleBarContent: >>>>>>views.length=" + views.length + ",isRemoveChildView=" + isRemoveChildView);
        if (isRemoveChildView) {
            layoutTitleBarContent.removeAllViews();
        }
        for (int i = 0; i < views.length; i++) {
            View view = views[i];
            if (view == null) {
                continue;
            }
            LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) view.getLayoutParams();
            Log.v(TAG, "addTitleBarContent: >>>>>>view[" + i + "]=" + view + ",layoutParams=" + layoutParams);
            if (layoutParams == null) {
                layoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            }

            int marginRight = 0;
            if (i < (views.length - 1)) {//最后一个View不设置右边距
                marginRight = layoutParams.rightMargin + getChildViewRightMargin();
            }
            Log.v(TAG, "addTitleBarContent: >>>>>>marginRight=" + marginRight);
            layoutParams.rightMargin = (marginRight > 0 ? marginRight : 0);
//            params.setMargins(0, 0, marginRight, 0);
            view.setLayoutParams(layoutParams);
            layoutTitleBarContent.addView(view);
        }
        return this;
    }

    /**
     * 添加 TitleBar 右部分自定义控件，默认清空 childView
     *
     * @param views 子视图
     * @return
     */
    public TpvSettingsTitleBarView addTitleBarRight(View... views) {
        Log.v(TAG, "addTitleBarRight: >>>>>>views.length=" + views.length);
        return addTitleBarRight(true, views);
    }

    /**
     * 添加 TitleBar 右部分自定义控件
     *
     * @param isRemoveChildView 添加前是否清空 childView，true-清空，false-不清空，顺序添加
     * @param views             子视图
     * @return
     */
    public TpvSettingsTitleBarView addTitleBarRight(boolean isRemoveChildView, View... views) {
        Log.d(TAG, "addTitleBarRight: >>>>>>views.length=" + views.length + ",isRemoveChildView=" + isRemoveChildView);
        if (isRemoveChildView) {
            layoutTitleBarRight.removeAllViews();
        }
        for (int i = 0; i < views.length; i++) {
            View view = views[i];
            if (view == null) {
                continue;
            }

            view.setFocusable(view.isEnabled());

            LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) view.getLayoutParams();
            Log.v(TAG, "addTitleBarRight: >>>>>>view[" + i + "]=" + view + ",layoutParams=" + layoutParams);
            if (layoutParams == null) {
                layoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            }

            int marginRight = 0;
            if (i < (views.length - 1)) {//最后一个View不设置右边距
                marginRight = layoutParams.rightMargin + getChildViewRightMargin();
            } else {
                marginRight = layoutParams.rightMargin;
//                marginRight = params.rightMargin + dp2px(getContext(), 30);
            }
            Log.v(TAG, "addTitleBarRight: >>>>>>marginRight=" + marginRight);
            layoutParams.rightMargin = (marginRight > 0 ? marginRight : 0);
//            params.setMargins(0, 0, marginRight, 0);
            view.setLayoutParams(layoutParams);
            layoutTitleBarRight.addView(view);
        }
        return this;
    }

    private void updateViewStatus() {
        btnBack.setEnabled(btnBack.getVisibility() == View.VISIBLE);
        int contentChildCount = layoutTitleBarContent.getChildCount();
        Log.d(TAG, "updateViewStatus: >>>>>>layoutTitleBarContent contentChildCount=" + contentChildCount);
        layoutTitleBarContent.setVisibility(contentChildCount > 0 ? VISIBLE : GONE);

        int rightChildCount = layoutTitleBarRight.getChildCount();
        Log.d(TAG, "updateViewStatus: >>>>>>layoutTitleBarRight rightChildCount=" + rightChildCount);

        if (rightChildCount > 0) {
            layoutTitleBarRight.setVisibility(VISIBLE);
            layoutTitleBarRight.setFocusable(true);
            int finalChildCount = rightChildCount;
            for (int i = 0; i < finalChildCount; i++) {
                //处理当添加的按钮全至少有一个是可以点击的时候，才可获得焦点
                if (layoutTitleBarRight.getChildAt(i).isEnabled()) {
                    layoutTitleBarRight.setFocusable(true);
                    break;
                }
            }
            layoutTitleBarRight.setOnFocusChangeListener(new OnFocusChangeListener() {
                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    Log.d(TAG, "onFocusChange: >>>>>>" + v + " focus state is " + hasFocus + ",finalChildCount=" + finalChildCount);
                    if (hasFocus) {
                        //聚焦在添加的第一个可操作的控件上
                        for (int i = 0; i < finalChildCount; i++) {
                            View childView = layoutTitleBarRight.getChildAt(i);
                            if (childView.isEnabled()) {
                                childView.requestFocus();
                                break;
                            }
                        }
                    }

                }
            });
        } else {
            layoutTitleBarRight.setVisibility(GONE);
            layoutTitleBarRight.setFocusable(false);
        }
    }

    private void initView() {
        inflate(getContext(), R.layout.layout_tpvsettings_titlebar_view, this);
        layoutTitleBarContent = findViewById(R.id.layout_titlebar_content);
        layoutTitleBarRight = findViewById(R.id.layout_titlebar_right);
        btnBack = findViewById(R.id.btn_titlebar_back);
        btnBack.setVisibility(isShowBack() ? View.VISIBLE : View.GONE);
        btnBack.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "onClick: >>>>>>btnBack[" + v + "] has clicked,iOnBackCallback=" + iOnBackCallback);
                if (iOnBackCallback != null) {
                    iOnBackCallback.onBack();
                }
            }
        });

        tvTitleContent = createTitleContentTextView();
        addTitleBarContent(tvTitleContent).setLayoutReadyOk();

    }

    /**
     * 提供 创建 titlecontent 的视图
     *
     * @return
     */
    public TextView createTitleContentTextView() {
        TextView textView = new TextView(getContext());
        textView.setSingleLine();
        textView.setEllipsize(TextUtils.TruncateAt.MIDDLE);
        textView.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
        textView.setTextColor(colorTitleContent(false));
        textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimensionPixelSize(R.dimen.size_text_middle));
        int padding = getResources().getDimensionPixelSize(R.dimen.dimen_space_small);
        textView.setPadding(padding, 0, padding, 0);
        textView.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
        textView.setLayoutParams(params);
        return textView;
    }

    /**
     * 创建 Titlebar 按钮视图，遵循 style_custom.xml 的 style_common_btn.StyleRadius 样式
     *
     * @return
     */
    public TextView createTitleRightBtnTextView() {
        TextView titlebarBtn = new TextView(getContext());
        titlebarBtn.setGravity(Gravity.CENTER);
        titlebarBtn.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
        titlebarBtn.setClickable(true);
        titlebarBtn.setSingleLine();
        titlebarBtn.setFocusable(true);
        titlebarBtn.setEllipsize(TextUtils.TruncateAt.MIDDLE);
        titlebarBtn.setBackground(getResources().getDrawable(R.drawable.selector_bg_rounded_rectangle_large));
        titlebarBtn.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
        int padding = getResources().getDimensionPixelSize(R.dimen.dimen_space_small);
        titlebarBtn.setPadding(padding, 0, padding, 0);

        titlebarBtn.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimensionPixelSize(R.dimen.size_text_small));
        titlebarBtn.setTextColor(getResources().getColorStateList(R.color.selector_btn_text_color));
        LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
        params.height = getResources().getDimensionPixelSize(R.dimen.dimen_btn_height_middle);
        params.width = getResources().getDimensionPixelSize(R.dimen.dimen_btn_width_middle);
        titlebarBtn.setLayoutParams(params);
        return titlebarBtn;
    }

    public Switch createRightSwitch() {
        Switch mSwitch = new Switch(getContext());
//        mSwitch.setPadding(dp2px(getContext(), 2), 0, dp2px(getContext(), 2), 0);
        mSwitch.setFocusable(true);
        mSwitch.setBackground(getResources().getDrawable(R.drawable.selector_bg_switch));
        mSwitch.setThumbResource(R.drawable.selector_switch_thumb);
        mSwitch.setTrackResource(R.drawable.selector_switch_track);
        mSwitch.setShowText(false);
        return mSwitch;
    }

    public ImageView createRightImage() {
        ImageView imageView = new ImageView(getContext());
        imageView.setImageResource(R.drawable.selector_ic_search);
        imageView.setFocusable(true);
        return imageView;
    }

    public void setOnBackCallback(IOnBackCallback callback) {
        iOnBackCallback = callback;
    }

    public void setOnPrivateMarkCallback(IOnPrivateMarkCallback callback) {
        this.iOnPrivateMarkCallback = callback;
        int childCount = layoutTitleBarContent.getChildCount();
        if (childCount <= 0 || iOnPrivateMarkCallback == null) {
            return;
        }
        layoutTitleBarContent.getChildAt(0).setOnTouchListener(new OnTouchListener() {
            private long lastTime = 0;
            private int priveMarkCount = 0;

            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (iOnPrivateMarkCallback == null) {
                    return false;
                }
                long curTime = new Date().getTime();
                if ((curTime - lastTime) < 500) {
                    priveMarkCount += 1;
                } else {
                    priveMarkCount = 1;
                    lastTime = 0;
                }
                Log.d(TAG, "onTouch: >>>>>>private mark lastTime=" + lastTime + ",priveMarkCount=" + priveMarkCount);
                lastTime = curTime;
                if (priveMarkCount >= 8) {
                    iOnPrivateMarkCallback.onPrivateMarkOpen();
                    priveMarkCount = 0;
                    lastTime = 0;
                }
                return false;
            }
        });
    }

    public int getChildViewRightMargin() {
        return childviewRightmargin;
    }

    /**
     * 是否显示 返回 箭头
     *
     * @return
     */
    public boolean isShowBack() {
        return true;
    }

    public void hideBack() {
        btnBack.setVisibility(GONE);
        btnBack.setEnabled(false);
    }

    public void setTitleContent(String titleContent) {
        tvTitleContent.setText(titleContent);
    }

    public int colorTitleContent(boolean isLight) {
        return isLight ? Color.parseColor("#FF4F94CD") : Color.parseColor("#2E343A");
    }

    /**
     * 可以指定 返回 按钮的遥控器向下目标，用于处理遥控器向下聚焦问题
     *
     * @param nextFocusDownId
     */
    public void setBackNextFocusDownId(int nextFocusDownId) {
        btnBack.setNextFocusDownId(nextFocusDownId);
    }

    /**
     * 根据分辨率从 dp 的单位 转成为 px(像素)
     */
    public int dp2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
}
